

/* global App, alertify */

App.register('CategoriesTable', CategoriesTable = {
    
    init: function() {
        this.setup();
    },
    
    setup: function() {
        var self = this;
        
        App.listen('categories.refresh', function() {
            window.history.go(0);
        });
        
        $("#categories-table tbody tr td.info").click(function() {
            $("#categories-table tbody tr").removeClass("selected");

            $(this).parents('tr').addClass("selected");

            var category_id = $(this).data('id');
            
            App.notify('category.load', category_id);
        });

        setTimeout(function() {
            $("#categories-table tbody tr:first td.info").click();
        }, 500);

        $("#add_btn").click(function(e) {
            e.preventDefault();
            
            App.notify("category.add");
        });

        $("#del_btn").click(function(e) {
            e.preventDefault();

            self.delete();
        });
    },
    
    selected: function() {
        var ids = [];

        $("#categories-table tbody tr td input:checked").each(function() {
            ids.push( $(this).val() );
        });

        return ids;
    },

    delete: function() {
        var selected = this.selected();

        if( selected && selected.length == 0 ) {
            alert("Please select categories to delete in order to continue");
            return;
        }

        confirm("Are you sure you would like to remove these categories?", function() {
            var url = $("#del_btn").attr("href");
            var params = {category_id: selected};

            $.ajax({
                url: url,
                data: params,
                type: 'post',
                dataType: 'json',
                success: function() {
                    $("#categories-table tbody tr td input:checked").each(function() {
                        $(this).parents("tr").remove();
                    });
                },
                error: function(xhr) {
                    alertify.error("Failed to remove selected accounts. Please try again later");
                }
            });
        });
        
    }
});

App.register('CategoryDetails', CategoryDetails = {
        
    init: function() {
        var self = this;
        
        self.setup();
        
        App.listen('category.load', function(category_id) {
            self.load(category_id);
        });
    },

    setup: function() {
        $("#category_view #edit_btn").click(function() {
            var category_id = $("#categories-table tbody tr.selected td.info").data('id');

            App.notify('category.edit', category_id);
        }).css({visibility: 'visible'});
    },

    load: function(category_id) {

        var url = $("#category_detail_url").val() + "/" + category_id;

        $("#category_view .panel-body").html("<div class='wrapper-lg text-center'><h4>Loading Profile. Please wait ...</h4></div>");

        $.ajax({
            url: url,
            type: 'post',
            success: function(res) {
                $("#category_view .panel-body").html(res);
                $("#category_view #edit_btn").css({visibility: 'visible'});
            },
            error: function(xhr) {
                $("#category_view .panel-body").html("<div class='wrapper-lg text-center'><h4>An Error Occured Whiles Loading Profile To View</h4></div>");
            }
        });
    }
});

App.register("CategoryEditor", CategoryEditor = {
    
    category_id: null,
    
    init: function() {
        var self = this;
        
        App.listen('category.add', function() {
            self.load();
        });
        
        App.listen('category.edit', function(category_id) {
            self.load(category_id);
        });
    },
    
    load: function(category_id) {
        var self = this;

        var url = $("#category_editor_url").val();
        var params = {};

        if( category_id ) {
            url += "/" + category_id;
        }
        
        // always cache the category_id even if null
        self.category_id = category_id;

        $("#category_view .panel-body").html("<div class='wrapper-lg'><h4>Loading Profile. Please wait ...</h4></div>");

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            success: function(res) {
                $("#category_view .panel-body").html(res);
                self.configure();
            },
            error: function(xhr) {
                $("#category_view .panel-body").html("<div class='wrapper-lg'><h3>An Error Occured Whiles Loading Profile To View</h3><div class='muted'>" + xhr.responseText + "</div></div>");
            }
        });
    },

    configure: function() {
        var self = this;

        if( $("#category_view #category_id").val() == "" ) {
            $("#category_view #category_name").friendurl({id: 'category_slug'});
        }
        
        $("#category_view #edit_btn").css({visibility: 'hidden'});

        $("#category_view #cancel-btn").click(function(e) {
            e.preventDefault();
            $("#categories-table tbody tr.selected td.info").click(); 
        });

        $("#category_view form").submit(function(e) {
            e.preventDefault();

            self.save();
        });

        $("#category_view #username").blur(function() {
            if( !$(this).hasClass("valid") && !$(this).hasClass("invalid") && this.checkValidity()  ) {
                self.checkUsername( $(this).val() );
            }

        }).keyup(function() {
            $(this).removeClass("valid invalid");
        });
    },

    save: function() {
        var self = this;

        if( $("#category_view .invalid").length > 0 ) {
            alert("This form has an error. Please check supplied inputs for validity");
            return;
        }

        var url = $("#category_view form").attr('action');
        var params = $("#category_view form").serialize();

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function(res) {
                if( typeof res['status'] != "undefined" ) {
                    if( res['status'] == 'success' ) {
                        if( self.category_id ) {
                            App.notify('category.load', self.category_id);
                        }   

                        else {
                            App.notify('categories.refresh');
                        }
                    }

                    else {
                        alertify.error(res['message']);
                    }
                }
                else {
                    alert(JSON.stringify(res));
                }
            },
            error: function() {
                alertify.error("Failed to save changes to membership category.");
            }
        });
    }
});

